<template>
  <el-dialog
    title="系统设置"
    :visible.sync="dialogVisible"
    :close-on-click-modal="!isInitialSetup"
    :close-on-press-escape="!isInitialSetup"
    :show-close="!isInitialSetup"
    width="1000px"
    append-to-body
    custom-class="warm-dialog system-settings-dialog"
    @close="handleClose"
  >
    <el-form ref="settingsForm" :model="settings" :rules="settingsRules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="系统标题" prop="sysTitle">
            <el-input v-model="settings.sysTitle" placeholder="请输入系统标题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公司名称" prop="cmpName">
            <el-input v-model="settings.cmpName" placeholder="请输入公司名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系电话" prop="customerPhone">
            <el-input
              v-model.trim="settings.customerPhone"
              placeholder="请输入联系电话"
              clearable
              @input="handlePhoneInput"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系邮箱" prop="customerEmail">
            <el-input
              v-model.trim="settings.customerEmail"
              placeholder="请输入联系邮箱"
              clearable
              @input="handleEmailInput"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="系统Logo" prop="sysLogo">
            <image-upload v-model="settings.sysLogo" :limit="1" :fileSize="2" :fileType="['png', 'jpg', 'jpeg']" />
            <div class="form-tip">建议上传正方形图片，大小不超过2MB</div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标题Logo" prop="titleLogo">
            <image-upload v-model="settings.titleLogo" :limit="1" :fileSize="2" :fileType="['png', 'jpg', 'jpeg']" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button v-if="!isInitialSetup" @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSave">{{ isInitialSetup ? '确认设置' : '保 存' }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import ImageUpload from "@/components/ImageUpload";

export default {
  name: 'SystemSettings',
  components: {
    ImageUpload
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    initialSettings: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      settings: {
        customerPhone: '',
        customerEmail: '',
        ...this.initialSettings
      },
      isInitialSetup: false,
      settingsRules: {
        sysTitle: [
          { required: true, message: "系统标题不能为空", trigger: "blur" }
        ],
        cmpName: [
          { required: true, message: "公司名称不能为空", trigger: "blur" }
        ],
        customerPhone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: ["blur", "change"] }
        ],
        customerEmail: [
          { required: true, message: "联系邮箱不能为空", trigger: "blur" },
          { type: 'email', message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }
        ]
      },
      originalSettings: {}
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit('update:visible', val);
      }
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.initSettings();
      }
    },
    initialSettings: {
      handler(val) {
        this.initSettings();
        // 如果没有 id，说明是初始设置
        this.isInitialSetup = !val.id;
      },
      immediate: true
    }
  },
  methods: {
    initSettings() {
      // 保存初始值，用于取消时恢复
      this.originalSettings = JSON.parse(JSON.stringify(this.initialSettings));
      
      const defaultSettings = {
        userId: 0,
        sysTitle: "密码管理系统",
        sysLogo: "",
        titleLogo: "",
        cmpName: "",
        customerPhone: "",
        customerEmail: ""
      };

      // 先设置默认值
      this.settings = { ...defaultSettings };
      
      // 然后用初始值覆盖默认值
      if (this.initialSettings) {
        Object.keys(this.initialSettings).forEach(key => {
          if (this.initialSettings[key] !== undefined && this.initialSettings[key] !== null) {
            this.settings[key] = this.initialSettings[key];
          }
        });
      }
      
      // 如果没有 id，说明是初始设置
      this.isInitialSetup = !this.settings.id;
    },
    handleClose() {
      this.dialogVisible = false;
      this.$emit('close');
    },
    handleCancel() {
      if (this.isInitialSetup) {
        this.$message.warning('请完成初始系统设置');
        return;
      }
      this.dialogVisible = false;
    },
    handleSave() {
      console.log('开始保存设置...');
      console.log('当前设置数据:', this.settings);

      // 先验证基本设置表单
      this.$refs.settingsForm.validate((valid1) => {
        if (!valid1) {
          console.log('基本设置验证失败');
          return false;
        }
        this.submitSettings();
      });
    },
    submitSettings() {
      try {
        console.log('提交设置数据...');
        const saveData = {
          ...this.settings,
          id: this.settings.id || null,
          userId: this.settings.userId || this.initialSettings.userId || 0,
          sysLogo: this.settings.sysLogo || this.initialSettings.sysLogo || '',
          titleLogo: this.settings.titleLogo || this.initialSettings.titleLogo || ''
        };
        console.log('提交的数据:', saveData);
        this.$emit('save', saveData);
        this.dialogVisible = false;
      } catch (error) {
        console.error('保存设置时出错:', error);
        this.$message.error('保存设置失败，请重试');
      }
    },
    handlePhoneInput(value) {
      // 移除非数字字符
      this.settings.customerPhone = value.replace(/\D/g, '').slice(0, 11);
    },
    handleEmailInput(value) {
      // 允许输入邮箱地址的有效字符
      this.settings.customerEmail = value.trim();
    }
  }
}
</script>

<style lang="scss" scoped>
/* 系统设置对话框样式 */
::v-deep .warm-dialog {
  border-radius: 12px;
  overflow: hidden;

  .el-dialog__header {
    background-color: #0d4ca4;
    padding: 16px 20px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);

    .el-dialog__title {
      color: #ffffff;
      font-weight: 600;
      font-size: 18px;
    }

    .el-dialog__headerbtn .el-dialog__close {
      color: rgba(255, 255, 255, 0.9);

      &:hover {
        color: #ffffff;
      }
    }
  }

  .el-dialog__body {
    padding: 25px 25px 10px;
  }

  .el-dialog__footer {
    padding: 15px 20px 20px;
    text-align: right;

    .el-button--primary {
      background: linear-gradient(135deg, #1a56b0, #0d4ca4);
      border: none;
      border-radius: 8px;
      padding: 10px 20px;
      font-weight: 500;
      box-shadow: 0 3px 8px rgba(13, 76, 164, 0.3);
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 12px rgba(13, 76, 164, 0.4);
      }

      &:active {
        transform: translateY(0);
      }
    }
  }
}

/* Tab 相关样式 */
::v-deep .el-tabs__nav-wrap {
  padding: 0 20px;

  &::after {
    height: 1px;
    background-color: #e8e8e8;
  }
}

::v-deep .el-tabs__item {
  font-size: 15px;
  height: 40px;
  line-height: 40px;

  &.is-active {
    color: #0d4ca4;
    font-weight: 600;
  }
}

::v-deep .el-tabs__active-bar {
  background-color: #0d4ca4;
  height: 3px;
  border-radius: 1.5px;
}

.form-tip {
  font-size: 12px;
  color: #5a7baf;
  margin-top: 5px;
}

.switch-label {
  margin-left: 10px;
  font-size: 14px;
  color: #333;
}

.input-suffix {
  margin-left: 10px;
  font-size: 14px;
  color: #333;
}

/* 针对系统设置表单样式的优化 */
::v-deep .system-settings-dialog {
  .el-form-item__label {
    color: #0d4ca4;
    font-weight: 500;
  }

  .el-input__inner {
    border-radius: 8px;
    border-color: #a0b8df;
    transition: all 0.3s;

    &:hover {
      border-color: #1a56b0;
    }

    &:focus {
      border-color: #0d4ca4;
      box-shadow: 0 0 0 2px rgba(13, 76, 164, 0.1);
    }
  }

  .el-input-number {
    width: 120px;
  }

  .el-switch__core {
    height: 22px;
    border-radius: 11px;
    width: 44px !important;
  }

  .el-switch.is-checked .el-switch__core::after {
    margin-left: 22px;
  }

  .el-switch__core::after {
    width: 18px;
    height: 18px;
    top: 1px;
    left: 1px;
    transition: all 0.3s;
  }
}
</style>

